package com.util;

import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import javax.jms.Connection;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.activemq.ActiveMQXAConnectionFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.park.model.Activemq;
import com.park.model.Data;
import com.park.model.Invoice;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class Active {
	private static Log logger = LogFactory.getLog(Active.class);
	
	private static final String userName = ActiveMQXAConnectionFactory.DEFAULT_USER;
    private static final String password = ActiveMQXAConnectionFactory.DEFAULT_PASSWORD;
    private static final String brokerURL = "tcp://120.25.153.123:61616";

     //public static void main(String[] args) throws JMSException {
     public void send() throws JMSException{
        //创建连接工厂类
        ConnectionFactory factory = new ActiveMQXAConnectionFactory(userName, password, brokerURL);
        //创建连接
        Connection connection = factory.createConnection();
        //启动连接
        connection.start();
        
        //创建会话对象session(事务transacted为true,参数2不生效)
        Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
        
        //目的地
        Topic topic = session.createTopic("248");
        
        //创建发送者
        MessageProducer producer = session.createProducer(topic);

        //for(int i=1;i<=1;i++) {
            //消息对象
            TextMessage message = session.createTextMessage("使用topic发送的消息");
            //发送消息
            producer.send(message);
            // 关闭资源
            producer.close();
            session.close();
            connection.close();
            System.out.println("发送测试:===="+message);
            //logger.info("activemq[发送数据:]"+message);
        //}
        //会话提交
//        session.commit();
        
        //关闭连接
        connection.close();
    }
 
    
    public static void main(String[] args) throws JMSException, IOException {
    //public void Invoice() throws JMSException, IOException{
        //创建连接工厂类
        ConnectionFactory factory = new ActiveMQXAConnectionFactory(userName, password, brokerURL);
        //创建连接
        Connection connection = factory.createConnection();
        //启动连接
        connection.start();
        
        //创建会话对象session(事务transacted为true,参数2不生效)
        Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
        
        //监听的消息名称
        Topic topic = session.createTopic("248");
        
        //接收消息对象
        MessageConsumer consumer = session.createConsumer(topic);
        System.out.println("topic消息。。。。");
        
        //通过监听器接收消息
        consumer.setMessageListener(new MessageListener() {
            public void onMessage(Message message) {
                TextMessage textMessage = (TextMessage)message;
                //获取消息
                Map<String, Object> argMap=new HashMap<>();
                try {
                    String msg = textMessage.getText();
                    /*System.out.println("接收消息:"+msg);
                    logger.info("activemq[接收数据:]"+msg);*/
                    if(msg!=null){
                    	argMap.put("code", "0000");
        				argMap.put("msg", "成功");
        				try{
		                    String url="http://test.datarj.com/webService/kptService";
		                    Gson gson=new Gson();
		                    Invoice invo=new Invoice();
		                    Data data=new Data();
		                    com.alibaba.fastjson.JSONObject json = com.alibaba.fastjson.JSONObject.parseObject(msg);
		                    Activemq mq = com.alibaba.fastjson.JSON.toJavaObject(json, Activemq.class);
		                    //System.out.println(mq.getExitDate());
		                    data.setCarNo(mq.getPlateNumber());
		                    data.setOrderDate(mq.getExitDate());
		                    data.setOrderNo("500102010003643");
		                    data.setRemark("上海百旺测试3643");
		                    DecimalFormat df = new DecimalFormat("##.00");
		                    String str=df.format(new BigDecimal(mq.getPaidMoney()));
		                    data.setTotalAmount(str);
		                    invo.setAppId("RJc0fbef6e08c0");
		                    invo.setClientNo("dsp_01");
		                    invo.setReqType("66");
		                    invo.setData(data);
		                    String key="14c1fca63c4a914267f76abaedf401ad";
		                	String datas=gson.toJson(invo.getData());
		                	String signSourceData="data="+datas+"&key="+key;
		                	String sign=DigestUtils.md5Hex(signSourceData);
		                	invo.setSign(sign);

		                	JSONObject jsons = (JSONObject) JSON.toJSON(invo);
//		                	JSONObject jsons = JSON.parseObject(datas);
		                	logger.info("json[转换后:]"+jsons);
		                	System.out.println("jsons:"+jsons);
		                	
		                	MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
//		                	JSONObject jsonObject = new JSONObject();
//		                	jsonObject.put("data",invo);
		                	
		                	logger.info("activemq[发送数据:]"+jsons);
		                	
		                	Request request = new Request.Builder()
		                			.url(url)
		                			.post(okhttp3.RequestBody.create(mediaType, jsons.toJSONString()))
		                			.build();
		                	OkHttpClient okHttpClient = new OkHttpClient();
		
		                	Call call = okHttpClient.newCall(request);
		                	call.enqueue(new Callback() {
		                		@Override
		                		public void onResponse(Call call, Response response) throws IOException {
		                			// TODO Auto-generated method stub
		                			logger.info("返回数据"+response.toString());
		                		}
		
		                		@Override
		                		public void onFailure(Call call, IOException e) {
		                			// TODO Auto-generated method stub
		                			logger.info("okHttpPost 请求错误:"+e.getMessage());
		                		}
		                		
		                	});
        				}catch(Exception e){
        					e.printStackTrace();
        				}
                    }else{
                    	argMap.put("code", "9999");
        				argMap.put("msg", "失败");
    				}
                    System.out.println("接收消息:"+msg);
                    logger.info("activemq[接收数据:]"+msg);
                } catch (JMSException e) {
                	e.printStackTrace();
                }
            }
        });
        //程序等待
        System.in.read();

        // 关闭资源
        consumer.close();
        session.close();
        connection.close();
        
    }
    
}
